<template>
  <div class="restaurant-list">
    <h1 class="page-title">餐厅列表</h1>
    <div class="search-box">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索餐厅名称或地址"
          clearable
          @keyup.enter="handleSearch"
          class="search-input"
      >
        <template #append>
          <el-button @click="handleSearch" class="search-button">搜索</el-button>
        </template>
      </el-input>
    </div>
    <div v-if="loading" class="loading-spinner">加载中...</div>
    <div v-else>
      <div class="restaurant-grid">
        <div
            v-for="restaurant in restaurants"
            :key="restaurant.restaurantId"
            class="restaurant-card"
            @click="openRestaurantDetail(restaurant)"
        >
          <div class="card-header">
            <h2 class="restaurant-name">{{ restaurant.name }}</h2>
            <span class="restaurant-status"
                  :class="{'open': restaurant.status === 1, 'closed': restaurant.status !== 1}">
              {{ restaurant.status === 1 ? '营业中' : '已打烊' }}
            </span>
          </div>
          <div class="card-body">
            <p class="restaurant-info"><strong>地址：</strong>{{ restaurant.address }}</p>
            <p class="restaurant-info"><strong>电话：</strong>{{ restaurant.phone }}</p>
            <p class="restaurant-info"><strong>描述：</strong></p>
            <div class="restaurant-description" v-html="restaurant.description"></div>
          </div>
        </div>
      </div>
      <div v-if="hasMore" class="load-more" @click="loadMore">
        加载更多
      </div>
      <div v-else class="no-more">
        没有更多数据了
      </div>
    </div>

    <!-- 餐厅详情模态框 -->
    <el-dialog
        v-model="isDetailVisible"
        :title="selectedRestaurant?.name"
        width="80%"
        :close-on-click-modal="false"
    >
      <div class="restaurant-detail-container">
        <!-- 左侧：餐厅详细信息 -->
        <div class="restaurant-info-section">
          <h3 class="section-title">餐厅信息</h3>
          <p><strong>地址：</strong>{{ selectedRestaurant?.address }}</p>
          <p><strong>电话：</strong>{{ selectedRestaurant?.phone }}</p>
          <p><strong>状态：</strong>
            <span :class="{'open': selectedRestaurant?.status === 1, 'closed': selectedRestaurant?.status !== 1}">
              {{ selectedRestaurant?.status === 1 ? '营业中' : '已打烊' }}
            </span>
          </p>
          <p><strong>描述：</strong></p>
          <div class="restaurant-description" v-html="selectedRestaurant?.description"></div>
          <p><strong>创建时间：</strong>{{ selectedRestaurant?.createdAt }}</p>
          <p><strong>更新时间：</strong>{{ selectedRestaurant?.updatedAt }}</p>
        </div>

        <!-- 右侧：菜品信息 -->
        <div class="dish-info-section">
          <h3 class="section-title">菜品列表</h3>
          <!-- 菜品搜索框 -->
          <div class="dish-search-box">
            <el-input
                v-model="dishSearchKeyword"
                placeholder="搜索菜品名称"
                clearable
                @keyup.enter="handleDishSearch"
                class="dish-search-input"
            >
              <template #append>
                <el-button @click="handleDishSearch" class="dish-search-button">搜索</el-button>
              </template>
            </el-input>
          </div>
          <div class="dish-grid">
            <div v-for="dish in filteredDishes" :key="dish.dishId" class="dish-card">
              <img :src="dish.imageUrl" alt="菜品图片" class="dish-image"/>
              <div class="dish-details">
                <h4 class="dish-name">{{ dish.name }}</h4>
                <p class="dish-price">价格：{{ dish.price }}元</p>
                <p class="dish-description">{{ dish.description }}</p>
                <div class="dish-actions">
                  <el-button type="primary" @click.stop="addToCart(dish)">加入购物车</el-button>
                  <el-button type="success" @click.stop="order(dish)">立即购买</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, computed} from 'vue';
import {apiGet} from '@/utils/api';
import type {Restaurant, Dish} from '@/types/entity';
import { addToCart, order } from '@/utils/cartAndOrder';

// 定义响应式的餐厅列表
const restaurants = ref<Restaurant[]>([]);
// 定义菜品列表
const dishes = ref<Dish[]>([]);

// 分页参数
const page = ref(1);
const pageSize = ref(10); // 每页显示10条数据
const hasMore = ref(true); // 是否还有更多数据
// 搜索关键词
const searchKeyword = ref('');
// 菜品搜索关键词
const dishSearchKeyword = ref('');
// 加载状态
const loading = ref(true);

// 餐厅详情相关
const isDetailVisible = ref(false);
const selectedRestaurant = ref<Restaurant | null>(null);

// 从后端获取餐厅数据
const fetchRestaurants = async () => {
  let parameter = {
    page: page.value,
    limit: pageSize.value,
    keyword: searchKeyword.value,
  };
  const {data} = await apiGet('/restaurant/findAll', parameter);
  if (data.data.length > 0) {
    restaurants.value = [...restaurants.value, ...data.data];
  } else {
    hasMore.value = false;
  }
  loading.value = false;
}

// 加载更多数据
function loadMore() {
  page.value += 1; // 加载下一页
  fetchRestaurants();
}

// 处理搜索
function handleSearch() {
  page.value = 1; // 重置分页
  hasMore.value = true; // 重置是否有更多数据
  restaurants.value = []; // 清空当前数据
  fetchRestaurants();
}

// 处理菜品搜索
function handleDishSearch() {
  // 这里可以根据 dishSearchKeyword 对菜品列表进行过滤
}

// 打开餐厅详情
async function openRestaurantDetail(restaurant: Restaurant) {
  selectedRestaurant.value = restaurant;
  // 拿到餐厅id查询菜品
  const {data} = await apiGet('/dish/getByRestaurantId', {restaurantId: restaurant.restaurantId});
  dishes.value = data;
  isDetailVisible.value = true;
}

// 计算属性：过滤后的菜品列表
const filteredDishes = computed(() => {
  return dishes.value.filter(dish =>
      dish.name.toLowerCase().includes(dishSearchKeyword.value.toLowerCase())
  );
});

// 在组件挂载时获取数据
onMounted(() => {
  fetchRestaurants();
});
</script>

<style scoped>
.restaurant-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  text-align: center;
  font-size: 2rem;
  margin-bottom: 20px;
  color: #333;
}

.search-box {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.search-input {
  width: 400px;
}

.search-button {
  background-color: #409EFF;
  color: white;
}

.restaurant-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.restaurant-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.restaurant-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.card-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.restaurant-name {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.restaurant-status {
  font-size: 0.9rem;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: bold;
}

.restaurant-status.open {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.restaurant-status.closed {
  background-color: #ffebee;
  color: #c62828;
}

.card-body {
  padding: 16px;
}

.restaurant-info {
  margin: 8px 0;
  font-size: 0.9rem;
  color: #555;
}

.restaurant-description {
  font-size: 0.9rem;
  color: #555;
  line-height: 1.5;
}

.load-more,
.no-more {
  text-align: center;
  padding: 10px;
  margin-top: 20px;
  background-color: #f1f1f1;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.load-more:hover {
  background-color: #e1e1e1;
}

.no-more {
  cursor: default;
  color: #888;
}

.loading-spinner {
  text-align: center;
  font-size: 1.2rem;
  color: #666;
  padding: 20px;
}

/* 餐厅详情模态框样式 */
.restaurant-detail-container {
  display: flex;
  gap: 20px;
  height: 600px; /* 固定高度 */
}

.restaurant-info-section {
  flex: 35; /* 左侧宽度占35% */
  padding: 16px;
  border-right: 1px solid #eee;
  overflow-y: auto; /* 超出部分显示滚动条 */
  height: 100%; /* 高度占满父容器 */
}

.dish-info-section {
  flex: 65; /* 右侧宽度占65% */
  padding: 16px;
  overflow-y: auto; /* 超出部分显示滚动条 */
  height: 100%; /* 高度占满父容器 */
}

.section-title {
  font-size: 1.2rem;
  margin-bottom: 16px;
  color: #333;
}

.dish-search-box {
  margin-bottom: 16px;
}

.dish-search-input {
  width: 100%;
}

.dish-search-button {
  background-color: #409EFF;
  color: white;
}

.dish-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.dish-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.dish-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.dish-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.dish-details {
  padding: 12px;
}

.dish-name {
  margin: 0;
  font-size: 1rem;
  color: #333;
}

.dish-price {
  margin: 4px 0;
  font-size: 0.9rem;
  color: #666;
}

.dish-description {
  margin: 4px 0;
  font-size: 0.8rem;
  color: #888;
}

.dish-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
}
</style>